<template>
  <!-- 底部带按钮的输入框 -->
  <van-action-sheet v-model="showComponent" class="custom-action" safe-area-inset-bottom>
    <div class="custom-tabs">
      <div class="custom-tabs__bar">
        <div
          class="custom-tab"
          @click="changeBar(item)"
          v-for="(item, index) in barList"
          :key="index"
          :class="currentBar == item.id ? 'van-tab--active' : ''"
        >
          <span class="custom-tab__text">{{ item.name }}</span>
        </div>
      </div>
      <div class="custom-tabs__content">
        <div class="sign-form" v-show="currentBar == 1">
          <div class="form-wrap">
            <textarea
              v-model="signinForm.signinRemark"
              rows="7"
              placeholder="备注(选填)"
              :readonly="this.dataList.length > 0"
            ></textarea>
            <!--  <van-uploader
              v-model="fileList"
              :before-read="beforeRead"
              :max-size="maxPhotoSize"
              :after-read="afterRead"
              @oversize="onOversize"
            /> -->
          </div>
          <button
            class="form-btn"
            type="primary"
            :disabled="genSignBtn.btnDisabled"
            :loading="saveLoading"
            round
            @click="save"
            >{{ genSignBtn.name }}</button
          >
          <div
            class="sign-tips danger"
            v-if="signinObj && signinObj.isSignStarted != 1"
          >
            <div>
              签到时间：{{ signinObj.startDay }} -
              {{ signinObj.endDay || "无限期" }}
            </div>
            <div>
              时间段：{{ signinObj.startHour }} -
              {{ signinObj.endHour || "23：59：59" }}
            </div>
          </div>
          <div v-else-if="!signinObj" class="danger">请联系管理员新建签到</div>
        </div>
        <div class="sign-list" v-show="currentBar == 2">
          <div class="progress-content" v-if="dataList.length > 0">
            <van-list
              v-model="listLoading"
              :finished="listFinished"
              :finished-text="dataList.length === 0 ? '' : '没有更多了'"
              @load="loadMore"
            >
              <div v-for="(item, index) in dataList" :key="index">
                <div  class="each" :class="index === dataList.length - 1 ? 'last' : ''">
                  <i></i>
                  <div>
                    <div class="tip">
                      <span class="mr10">{{ item.signinTime }}</span>
                      <span>{{ getDeviceType(item.signinType) }}签到</span>
                    </div>
                    <div class="content">{{ item.signName }}</div>
                    <div class="tip mt5" v-if="item.signinRemark">
                      备注：{{ item.signinRemark }}
                    </div>
                  </div>
                </div>
              </div>
            </van-list>
          </div>
          <Data-empty v-if="listFinished && dataList.length === 0"></Data-empty>
        </div>
      </div>
    </div>
  </van-action-sheet>
</template>

<script>
import { parse, stringify, beforePicUpload } from "@/assets/js/util";
import { deviceList } from "@/assets/js/constant";
import DataEmpty from "@/components/common/DataEmpty";
import VanActionSheet from "@/components/vant/van-action-sheet/van-action-sheet.vue";
import VanList from "@/components/vant/van-list/van-list.vue";
export default {
  data() {
    return {
      maxPhotoSize: 10 * 1024 * 1024,
      showComponent: false,
      currentBar: 1,
      signinForm: {},
      saveLoading: false,
      barList: [
        { name: "打卡签到", id: 1 },
        { name: "签到记录", id: 2 }
      ],
      listLoading: false,
      listFinished: false,
      pageLoading: false,
      page: {
        pageNumber: 1,
        pageSize: 10
      },
      dataList: [],
      fileList: []
    };
  },

  components: {
    VanList,
    VanActionSheet,
    DataEmpty
  },

  props: {
    showAction: {
      type: Boolean,
      default: false
    },
    courseId: {
      type: String,
      default: ""
    },
    mainServer: {
      type: Object,
      default: () => {}
    },
    signinObj: {
      type: Object,
      default: () => null
    },
    courseInfo: {
      type: Object,
      default: () => {}
    }
  },

  mounted() {
    this.getSigninList(true);
  },

  computed: {
    // 签到按钮状态
    // genSignBtn() {
    //   return this.signinObj
    //     ? this.signinObj.isSignStarted == 2
    //       ? "已结束"
    //       : this.signinObj.isUserSingined == 1
    //       ? "已签到"
    //       : "签到"
    //     : "";
    // }
    // 签到按钮状态
    genSignBtn() {
      let data = {name: '', btnDisabled: true, btnStyle: 'disabled'};
      if (this.signinObj) {
        if (this.signinObj.isSignStarted == 2) {
          data.name = '已结束'
        } else if (this.signinObj.isSignStarted == 0) {
          data.name = '未开始'
        } else if (
          this.courseInfo.courseConfig &&
          this.courseInfo.courseConfig.isSignin == "1" &&
          this.courseInfo.isSigned == "2"
        ) {
          data = {name: '开始签到', btnDisabled: false, btnStyle: 'primary'};
        } else if (
          this.courseInfo.courseConfig &&
          this.courseInfo.courseConfig.isSignin == "1" &&
          this.courseInfo.isSigned == "1"
        ) {
          data.name = '已签到'
        }
      }
      return data;
    }
  },

  methods: {
    changeBar(item) {
      this.currentBar = item.id;
    },

    getDeviceType(type) {
      let res = deviceList.find(item => item.type == type);
      return res ? res.name : "";
    },

    onOversize(file) {
      this.$toast.warning(
        `文件大小不能超过${this.maxPhotoSize / 1024 / 1024}Mb`
      );
    },

    beforeRead(file) {
      return beforePicUpload(file, this);
    },

    afterRead(file) {
      let data = new FormData();
      data.append("laTDeLXS", file.file);
      let url =
        this.mainServer.serverDomain + this.$api.basics.content_server_url();
      this.$api.basics
        .newUpload(url, data)
        .then(res => {
          this.fileList = [{ url: res.fileContentUrl, name: "" }];
        })
        .catch(e => {
          this.fileList = [];
        });
    },

    // 签到
    save() {
      let params = parse(stringify(this.signinForm));
      params.courseId = this.courseId;
      if (this.fileList.length > 0) {
        params.signinImages = this.fileList[0].url;
      }
      this.saveLoading = true;
      // 1PC、2WAP、3Android、4iOS
      params.signDevice = 2;
      this.$api.course
        .signinCreate(params)
        .then(res => {
          this.dataList = [];
          this.signinForm = {};
          this.getSigninList(true)
          this.saveLoading = false;
          this.$emit("success");
          this.getSigninList(true);
        })
        .catch(e => {
          this.saveLoading = false;
          this.$toast.fail("签到失败" + (e.msg ? "：" + e.msg : ""));
        });
    },

    // 获取签到记录列表
    getSigninList(loadNew = false) {
      if (loadNew === true) {
        this.listFinished = false;
        this.page.pageNumber = 1;
        this.pageLoading = true;
      }
      let params = Object.assign({ courseId: this.courseId }, this.page);
      this.$api.course
        .userCourseSigninList(params)
        .then(res => {
          if (loadNew) this.dataList = [];
          this.dataList = this.dataList.concat(res.list || []);
          this.signinForm.signinRemark = this.dataList[0].signinRemark;
          this.noMoreState(res);
          this.pageLoading = false;
        })
        .catch(e => {
          this.pageLoading = false;
          this.listLoading = false;
          this.listFinished = true;
        });
    },

    // 加载更多
    loadMore: function() {
      if (!this.listFinished) this.getSigninList();
    },

    noMoreState: function(res) {
      if (
        res.totalPage <= this.page.pageNumber ||
        (res.list && res.list.length === 0)
      ) {
        this.listFinished = true;
      } else {
        this.page.pageNumber++;
      }
    }
  },
  watch: {
    showAction(val) {
      this.showComponent = val;
      if (!val) {
      }
    },
    showComponent(val) {
      if (!val) {
        this.$emit("hide");
      }
    },
    /*currentBar(val) {
      if (val == 2 && this.dataList.length == 0) {
      }
    }*/
    //    signinObj(val) {
    //        console.log(val)
    //    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/static/css/variable.scss";
.custom-action {
  min-height: 48%;
  .custom-tabs {
    @include customTabs;
	padding-top: 20px;
  }
  .progress-content {
    @include progressContent;
	.van-list{
		height: 170px;
	}
  }
  .sign-form {
    padding: 20px;
    .form-wrap {
      border-radius: 12px;
      border: 1px solid #eeeeee;
      height: 170px;
      padding: 5px;
      textarea {
        width: 100%;
        padding: 5px;
        height: auto;
      }
      :deep(.van-uploader__upload),
      :deep(.van-uploader__preview-image) {
        border-radius: 10px;
        width: 65px;
        height: 65px;
      }
    }
    .form-btn {
      margin-top: 26px;
      height: 40px;
      width: 100%;
    }
    .sign-tips {
      font-size: 14px;
      margin: 6px auto 0;
    }
  }
  .sign-list {
    padding: 0 20px 20px 10px;
  }
}
</style>
